package io.sundial.console.taskgroup.service;

import io.sundial.console.Pagination;
import io.sundial.console.taskgroup.core.Taskgroup;
import io.sundial.console.taskgroup.dao.TaskgroupRepository;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;

/**
 * 任务组服务实现
 *
 * @author Payne 646742615@qq.com
 * 2019/1/4 16:42
 */
@Service
@Transactional(readOnly = true)
public class TaskgroupServiceBean implements TaskgroupService {

    @Resource
    private TaskgroupRepository taskgroupRepository;

    @Override
    public Taskgroup find(String name) {
        return taskgroupRepository.getOne(name);
    }

    @Transactional(rollbackFor = Throwable.class)
    @Override
    public void save(Taskgroup taskgroup) {
        taskgroupRepository.save(taskgroup);
    }

    @Override
    public Pagination<Taskgroup> search(int pageNo, int pageSize, String keyword) {
        Pageable pageable = PageRequest.of(pageNo - 1, pageSize, Sort.by(Sort.Order.desc("dateCreated")));
        Page<Taskgroup> page = taskgroupRepository.search("%" + (keyword != null ? keyword : "") + "%", pageable);
        return new Pagination<>(page.getTotalElements(), page.getContent());
    }

    @Transactional(rollbackFor = Throwable.class)
    @Override
    public void remove(String name) {
        taskgroupRepository.delete(name);
    }

    @Transactional(rollbackFor = Throwable.class)
    @Override
    public void update(String name, Taskgroup taskgroup) {
        taskgroupRepository.update(
                name,
                taskgroup.getPeriod(),
                taskgroup.getExpression(),
                taskgroup.getDescription(),
                new Date()
        );
    }
}
